import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2015/12/31.
 */
public class OrnamentalGarden {

    public static void main(String[] args) throws Exception {
        ExecutorService exec = Executors.newCachedThreadPool();
        //加大线程数，增加执行时间，放大问题
        for (int i = 0; i < 20000; i++) {
            exec.execute(new Entrance(i));
        }
        //Run for a while ,then stop and collect the data
        TimeUnit.SECONDS.sleep(5);
        Entrance.cancel();
        exec.shutdown();
        if (!exec.awaitTermination(250, TimeUnit.MILLISECONDS)) {
            System.out.println("Some tasks were not terminated!");
        }
        System.out.println("Total: " + Entrance.getTotalCount());
        System.out.println("Sum of Entrances: " + Entrance.sumEntrances());
    }

}

class Count {
    private int count = 0;
    private Random rand = new Random(47);

    //Remove the synchronized keyword to see counting fail
    public synchronized int increament() {
        int temp = count;
        //yield half the time
        if (rand.nextBoolean()) {
            Thread.yield();
        }
        return (count = ++temp);
        //我使用++count并去掉synchronized没有出问题，但是++count不是原子性，原理上应该会出并发问题，可能是我的并发不多原因
        //PS:加大并发，增加执行时间，最后数值也对不上了，我的猜想是对的
        //return ++count ;
    }

    public synchronized int value() {
        return count;
    }
}

class Entrance implements Runnable {
    private static Count count = new Count();
    private static List<Entrance> entrances = new ArrayList<Entrance>();
    private int number = 0;
    private final int id;
    private static volatile boolean canceled = false;

    public static void cancel() {
        canceled = true;
    }

    public Entrance(int id) {
        this.id = id;
        entrances.add(this);
    }

    @Override
    public void run() {
        while (!canceled) {
            synchronized (this) {
                ++number;
            }
            count.increament();
            //我放大了并发，由于控制台输出是原子性，我注释掉这个输出。减少影响
            // System.out.println(this + " Total:" + count.increament());
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                System.out.println("sleep interrupte");
            }
        }
        System.out.println("Stoping " + this);
    }

    public synchronized int getValue() {
        return number;
    }

    @Override
    public String toString() {
        return "Entrance " + id + ":" + getValue();
    }

    public static int getTotalCount() {
        return count.value();
    }

    public static int sumEntrances() {
        int sum = 0;
        for (Entrance entrance : entrances) {
            sum += entrance.getValue();
        }
        return sum;
    }
}